package com.lagou.initializer;

import com.lagou.initializer.MyWebApplicationInitializer;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 当实现了Servlet3.0规范的容器（比如Tomcat7及以上版本）启动时，
 * 会通过SPI扩展机制自动扫描所有jar包里META-INF/services/javax.servlet.ServletContainerInitializer
 * 文件中指定的全路径类（该类需实现ServletContainerInitializer接口），并实例化该类，并回调类中的onStartup方法。
 */
//@HandlesTypes({WebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
        public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses,ServletContext servletContext) throws ServletException {
            // 用于存放 感兴趣的类 的list 集合
            List<WebApplicationInitializer> initializers = new LinkedList();

            Iterator var4;
            if (webAppInitializerClasses != null) {
                var4 = webAppInitializerClasses.iterator();
                // 遍历感兴趣的类
                while(var4.hasNext()) {
                    Class<?> waiClass = (Class)var4.next();
                    // 判断是不是接口，是不是抽象类，是不是该类型
                    if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                        try {
                            // 实例化每个WebApplicationInitializer并添加到initializers中
                            initializers.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(waiClass, new Class[0]).newInstance());
                        } catch (Throwable var7) {
                            throw new ServletException("Failed to instantiate WebApplicationInitializer class", var7);
                        }
                    }
                }
            }

            if (initializers.isEmpty()) {
                servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
            } else {
                servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
                AnnotationAwareOrderComparator.sort(initializers);
                var4 = initializers.iterator();

                // 依次调用 WebApplicationInitializer 的onStartup方法
                while(var4.hasNext()) {
                    WebApplicationInitializer initializer = (WebApplicationInitializer)var4.next();
                    initializer.onStartup(servletContext);
                }

            }
        }
    //}

}
